# 文件名: data_structures_examples.py
# 说明: Python3 数据结构示例合集

print("\n--- 示例1: 列表 (List) ---")
# 定义列表（有序、可变、允许重复）
fruits = ["apple", "banana", "cherry"]
print("原始列表:", fruits)

# 增删改查操作
fruits.append("orange")          # 追加元素
fruits.insert(1, "grape")        # 插入元素
fruits[2] = "mango"              # 修改元素
popped = fruits.pop(3)           # 删除索引3的元素并返回
print("修改后列表:", fruits)      # ['apple', 'grape', 'mango', 'orange']
print("被删除的元素:", popped)    # cherry

# 列表切片
print("前两个元素:", fruits[:2])  # ['apple', 'grape']
print("逆序:", fruits[::-1])      # ['orange', 'mango', 'grape', 'apple']

# 列表推导式
squares = [x**2 for x in range(5)]
print("平方列表:", squares)       # [0, 1, 4, 9, 16]


print("\n--- 示例2: 元组 (Tuple) ---")
# 定义元组（有序、不可变、允许重复）
dimensions = (1920, 1080)
print("原始元组:", dimensions)

# 元组解包
width, height = dimensions
print(f"宽度: {width}, 高度: {height}")  # 宽度: 1920, 高度: 1080

# 元组作为字典键（不可变性保障哈希安全）
locations = {
    (35.6895, 139.6917): "东京",
    (40.7128, -74.0060): "纽约"
}
print("坐标查询:", locations[(35.6895, 139.6917)])  # 东京


print("\n--- 示例3: 字典 (Dict) ---")
# 定义字典（键值对、无序、键唯一）
student = {
    "name": "Alice",
    "age": 20,
    "courses": ["Math", "CS"]
}
print("原始字典:", student)

# 增删改查操作
student["gender"] = "Female"       # 添加键值对
student["age"] = 21                # 修改值
del student["courses"]             # 删除键
print("修改后字典:", student)       # {'name': 'Alice', 'age': 21, 'gender': 'Female'}

# 安全访问
print("get方法:", student.get("phone", "N/A"))  # N/A

# 字典推导式
square_dict = {x: x**2 for x in range(5)}
print("平方字典:", square_dict)     # {0:0, 1:1, 2:4, 3:9, 4:16}


print("\n--- 示例4: 集合 (Set) ---")
# 定义集合（无序、元素唯一）
colors = {"red", "blue", "green"}
print("原始集合:", colors)

# 集合操作
colors.add("yellow")              # 添加元素
colors.remove("blue")             # 删除元素
print("修改后集合:", colors)       # {'red', 'green', 'yellow'}

# 集合运算
a = {1, 2, 3}
b = {2, 3, 4}
print("并集:", a | b)              # {1,2,3,4}
print("交集:", a & b)              # {2,3}
print("差集:", a - b)              # {1}


print("\n--- 示例5: 其他高级数据结构 ---")
# 队列 (Queue) - 使用 collections.deque
from collections import deque
queue = deque(["A", "B", "C"])
queue.append("D")                  # 入队
queue.popleft()                    # 出队
print("队列:", queue)              # deque(['B', 'C', 'D'])

# 堆 (Heap) - 使用 heapq 模块
import heapq
nums = [3, 1, 4, 1, 5]
heapq.heapify(nums)                # 转换为堆结构
print("堆顶元素:", heapq.heappop(nums))  # 1

# 默认字典 (DefaultDict)
from collections import defaultdict
word_count = defaultdict(int)
for word in ["apple", "banana", "apple"]:
    word_count[word] += 1
print("单词计数:", word_count)      # defaultdict(<int>, {'apple':2, 'banana':1})